const fs = require('fs');
const http = require('http');
const url = require('url');
const template = require('art-template')


var comments = [
    {
        name:'张三',
        message:'fesefsf',
        dataTime:'2020-9-11'
    },
    {
        name:'张三1',
        message:'fesefsffesfs',
        dataTime:'2020-9-11'
    },
    {
        name:'张三2',
        message:'fesefseffessf',
        dataTime:'2020-9-11'
    }
]
var read = function (_url) {
    try {
        var data = fs.readFileSync(_url);
        return data;
    } catch (error) {
        try {
            var data = fs.readFileSync('./views/404-Page/index.html');
            return data;
        } catch (error) {
            return '404 Not Found';
        }
    }
}

     
// 创建服务器
http
    .createServer(function (req, res) {
        var req_url = req.url;
        var parseObj = url.parse(req_url, true)
        var pathname = parseObj.pathname
        
        if (req_url === '/' || req_url === '/index.html') {
            data = read('./views/message-Page/index.html')
            if (data === '404 Not Found') {
                return res.end(data);
            }
            var htmlStr = template.render(data.toString(), {
                comments:comments
            })
            res.end(htmlStr);
        } else if (req_url.indexOf('/public/') === 0) {
            res.end(read('.'+req_url));
        } else if (pathname === '/pinglun') {
            var comment = JSON.stringify(parseObj.query);
            comment = JSON.parse(comment);
            comment.dataTime = '2020-10-11';
            comments.unshift(comment);
            res.statusCode = 302;
            res.setHeader('Location', '/');
            res.end()
        } else {
            res.end('404 Not Found');
        }
    })
    
// 开启服务器
    .listen(2000, function () {
        console.log('running....');
    })
